package admin

import (
	"github.com/gin-gonic/gin"
	"go-project/dto/requrest"
	"go-project/pkg/utils"
	"go-project/service"
	"net/http"
	"strconv"
	"strings"
)

type ArticleController struct {
}

func (ArticleController) List(c *gin.Context) {
	pagination := requrest.GeneratePaginationFormRequest(c)
	articleSearchRequest := requrest.ArticleSearchRequest{Pagination: pagination}
	err := c.ShouldBind(&articleSearchRequest)
	if err != nil {
		return
	}
	article := &service.Article{}
	lists, count, err := article.FindLists(&articleSearchRequest)
	utils.PaginationSuccess(c, count, lists, pagination)
}

func (ArticleController) Add(c *gin.Context) {
	articleInsertRequest := &requrest.ArticleInsertRequest{}
	errors := articleInsertRequest.BindAndValidate(c)
	if errors != nil {
		return
	}
	insertId, err := service.Article{}.Add(articleInsertRequest)
	if err != nil {
		utils.Error(c, utils.ERROR, "添加失败", http.StatusOK)
		return
	}
	utils.Success(c, gin.H{
		"id": insertId,
	}, http.StatusCreated)
}

func (ArticleController) Del(c *gin.Context) {
	value := c.Query("id")
	if value == "" {
		utils.Error(c, utils.ERROR, "id不能为空", http.StatusOK)
		return
	}
	id, err := strconv.Atoi(value)
	if err != nil {
		utils.Error(c, utils.ERROR, err.Error(), http.StatusOK)
		return
	}
	rowsAffected, err := service.Article{}.Del(uint(id))
	if err != nil {
		utils.Error(c, utils.ERROR, err.Error(), http.StatusOK)
		return
	}
	if rowsAffected <= 0 {
		utils.Error(c, utils.ERROR, "删除失败", http.StatusOK)
	}
	utils.Success(c, gin.H{}, http.StatusNoContent)
}

func (ArticleController) BatchDelete(c *gin.Context) {
	value := c.Query("ids")
	if value == "" {
		utils.Error(c, utils.ERROR, "id不能为空", http.StatusOK)
		return
	}
	ids := strings.Split(value, ",")
	var new_ids []int
	for _, id := range ids {
		id, _ := strconv.Atoi(id)
		new_ids = append(new_ids, id)
	}
	rowsAffected, err := service.Article{}.BatchDelByIds(new_ids)
	if err != nil {
		utils.Error(c, utils.ERROR, err.Error(), http.StatusOK)
		return
	}
	if rowsAffected <= 0 {
		utils.Error(c, utils.ERROR, "删除失败", http.StatusOK)
	}
	utils.Success(c, gin.H{}, http.StatusNoContent)
}

func (ArticleController) Edit(c *gin.Context) {
	id, err := strconv.Atoi(c.Query("id"))
	if err != nil {
		c.HTML(http.StatusNotFound, "admin.error", gin.H{
			"error": err.Error(),
		})
		return
	}
	model, err := service.Article{}.Get(uint(id))

	if err != nil {
		c.HTML(http.StatusBadGateway, "admin.error", gin.H{
			"error": err.Error(),
		})
		return
	}

	c.HTML(http.StatusOK, "article.edit", gin.H{
		"model": model,
	})
}

func (ArticleController) Update(c *gin.Context) {
	articleUpdateRequest := &requrest.ArticleUpdateRequest{}
	err := articleUpdateRequest.BindAndValidate(c)
	if err != nil {
		return
	}
	update_id, err := service.Article{}.Update(articleUpdateRequest)
	if err != nil {
		utils.Error(c, utils.ERROR, err.Error(), http.StatusOK)
		return
	}
	utils.Success(c, gin.H{
		"id": update_id,
	}, http.StatusOK)
}
